<template>
  <div>
    <h1>助理模块</h1>
    <el-tabs v-model="activeName" >
      <el-tab-pane label="归还申请" name="first">
        <el-form :inline="true" :model="ReturnAccessSearch">
          <el-form-item label="实验编号">
            <el-input v-model="ReturnAccessSearch.ExpId" placeholder="请填写实验编号"></el-input>
          </el-form-item>
          <el-form-item label="功能单元编号">
            <el-input v-model="ReturnAccessSearch.UnitId" placeholder="请填写实验名称"></el-input>
          </el-form-item>
          <el-form-item label="功能单元名称">
            <el-input v-model="ReturnAccessSearch.UnitName" placeholder="请填写功能单元名称"></el-input>
          </el-form-item>
          <el-form-item>
            <el-switch v-model="ReturnAccessSearch.StateIf" active-text="仅显示未归还实验" inactive-text=""></el-switch>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit" icon="el-icon-search">查询</el-button>
          </el-form-item>
        </el-form>
        <el-table
            :data="tableData"
            height="500"
            border
            style="width: 100%"
            :header-cell-style="{textAlign: 'center'}"
            :cell-style="{ textAlign: 'center' }"
            :row-class-name="tableRowClassName">
          <el-table-column
              prop="labid"
              label="实验编号"
              sortable
              width="240">
          </el-table-column>
          <el-table-column
              prop="procedureid"
              label="功能单元编号"
              sortable
              width="240">
          </el-table-column>
          <el-table-column
              prop="procedurename"
              label="功能单元名称"
              sortable
              width="240">
          </el-table-column>
          <el-table-column
              prop="procedurestate"
              label="功能单元状态"
              sortable
              width="240">
          </el-table-column>
          <el-table-column
              prop="procedureisdone"
              label="操作"
              width="240">
            <template #default="scope">
              <el-button size='small' @click="handleClick(data, scope.row)" el-button type="info" plain> 提交申请</el-button>
              <i class="el-icon-s-flag" v-if="scope.row.procedureisdone==1"></i>
              <i class="el-icon-more" v-if="scope.row.procedureisdone==2"></i>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>


      <el-tab-pane label="状态反馈" name="second">
        <center>
          <div style="max-width: 600px">
            <el-form :model="ruleForm" status-icon :rules="rules" label-position="left" ref="ruleForm"
                     label-width="100px" class="ruleForm">
              <el-form-item label="实验编号">
                <el-input size="medium" v-model="ruleForm.expid" :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="功能单元编号">
                <el-input size="medium" v-model="ruleForm.unitid" :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="功能单元名称">
                <el-input size="medium" v-model="ruleForm.unitname" :disabled="true"></el-input>
              </el-form-item>
              <el-row>
                <el-col span="50">
                  <el-form-item label="实验状态">
                    <el-select v-model="ruleForm.unitstate" placeholder="请选择" >
                      <el-option-group
                          v-for="group in options"
                          :key="group.label"
                          :label="group.label">
                        <el-option
                            v-for="item in group.options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                      </el-option-group>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="备注">
                <el-input
                    type="textarea"
                    :rows="3"
                    placeholder="备注"
                    maxlength="100"
                    show-word-limit
                    v-model="ruleForm.textarea">
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitForm(ruleForm)">提交</el-button>
              </el-form-item>
            </el-form>

          </div>

        </center>

      </el-tab-pane>
      <el-tab-pane label="功能单元管理" name="third">
        <el-form :inline="true" :model="ProManageSearch">
          <el-form-item label="实验编号">
            <el-input v-model="ProManageSearch.ExpId" placeholder="请填写实验编号"></el-input>
          </el-form-item>
          <el-form-item label="功能单元编号">
            <el-input v-model="ProManageSearch.UnitId" placeholder="请填写实验名称"></el-input>
          </el-form-item>
          <el-form-item label="功能单元名称">
            <el-input v-model="ProManageSearch.UnitName" placeholder="请填写功能单元名称"></el-input>
          </el-form-item>
          <el-form-item>
            <el-switch v-model="ProManageSearch.StateIf" active-text="仅显示出错实验" inactive-text=""></el-switch>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit_two" icon="el-icon-search">查询</el-button>
          </el-form-item>
        </el-form>
        <el-table
            :data="tableProManage"
            height="500"
            border
            style="width: 100%"
            :header-cell-style="{textAlign: 'center'}"
            :cell-style="{ textAlign: 'center' }"
            :row-class-name="tableRowClassName">
            <el-table-column
                prop="labid"
                label="实验编号"
                sortable
                width="240">
            </el-table-column>
            <el-table-column
                prop="procedureid"
                label="功能单元编号"
                sortable
                width="240">
            </el-table-column>
            <el-table-column
                prop="procedurename"
                label="功能单元名称"
                sortable
                width="240">
            </el-table-column>
            <el-table-column
                prop="procedurestate"
                label="功能单元状态"
                sortable
                width="240">
            </el-table-column>
            <el-table-column
                label="操作"
                width="240">
              <template #default="scope">
                <el-button size='mini' @click="handleDelete(scope.row)" el-button type="info" plain>撤销该单元</el-button>
                <el-button size='mini' @click="handleDeleteAll(scope.row)" el-button type="info" plain>撤销后续单元</el-button>
              </template>
            </el-table-column>
          </el-table>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import {ElMessage} from "element-plus";
//import {ElMessageBox} from "element-plus";
import { ref } from 'vue';
import {get} from "@/utils/http";

export default {
  name: "doAssist",
  data(){
    return{
      ReturnAccessSearch: {
        UnitName: '',
        ExpId: '',
        UnitId: '',
        StateIf: 0,
      },
      ProManageSearch: {
        UnitName: '',
        ExpId: '',
        UnitId: '',
        StateIf: 0,
      },
      button_flag: 1,
      visible: false,
      options: [{
        label: '查验员',
        options: [{
          value: '资源不足',
          label: '资源不足'
        }]
      }, {
        label: '独立PI',
        options: [{
          value: '实验失败',
          label: '实验失败'
        }, ] },
        {
          label: '科研助理',
          options: [{
            value: '数据有误',
            label: '数据有误'
          }, {
            value: '实验完成',
            label: '实验完成'
          }] }],
      ruleForm: {
        expid: 'EXP1',
        unitid: 'UN3',
        unitname: '猪心分离',
        unitstate: '',
        textarea: ref(''),
      },
      tableData: [],
      tableProManage: []
    };
  },
  created() {
    this.exp_id = this.$route.params.exp_id;
    this.pro_id = this.$route.params.pro_id;
    this.pro_name = this.$route.params.pro_name;
    this.pi_id = this.$route.params.pi_id;
    if (this.exp_id === undefined){
      this.exp_id = sessionStorage.getItem("exp_id");
    }
    else {
      sessionStorage.setItem("exp_id",this.exp_id)
    }
    if (this.pro_id === undefined){
      this.pro_id = sessionStorage.getItem("pro_id");
    }
    else {
      sessionStorage.setItem("pro_id",this.pro_id)
    }
    if (this.pro_name === undefined){
      this.pro_name = sessionStorage.getItem("pro_name");
    }
    else {
      sessionStorage.setItem("pro_name",this.pro_name)
    }
    if (this.pi_id === undefined){
      this.pi_id = sessionStorage.getItem("pi_id");
    }
    else {
      sessionStorage.setItem("pi_id",this.pi_id)
    }
    this.ruleForm.expid = this.exp_id;
    this.ruleForm.unitid = this.pro_id;
    this.ruleForm.unitname = this.pro_name;
  },
  methods:{
    handleClick(data, row){
      let that = this;
      let router_target = "returnRes";
      if(row.procedurestate === '实验完成'){
        row.procedureisdone = '1';
        that.$message({
          type: "success",
          message: "提交成功!"
        });
        that.$router.push({
          name: router_target,
          params: {
            exp_id: that.exp_id,
            pro_id: that.pro_id,
            pro_name: that.pro_name,
            pi_id: that.pi_id,
          }
        })
      }
      else{
        that.$confirm("该实验尚未完成，是否提交申请?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
            .then(() => {
              row.procedureisdone = '1';
              that.$message({
                type: "success",
                message: "提交成功!"
              });
              that.$router.push({
                name: router_target,
                params: {
                  exp_id: that.exp_id,
                  pro_id: that.pro_id,
                  pro_name: that.pro_name,
                  pi_id: that.pi_id,
                }
              })
            })
            .catch(() => {
              row.procedureisdone = '2';
              that.$message({
                type: "info",
                message: "已取消提交"
              });
            });
      }
    },
    onSubmit() {
      let that = this;
      let state = '';
      that.tableData = [];
      if(that.ReturnAccessSearch.ExpId.slice(0,3) != 'EXP' && that.ReturnAccessSearch.ExpId != ''){
        ElMessage.warning({
          showClose: true,
          message: "实验编号应以EXP开头！",
          type: "warning",
          center: true
        })
      }
      if(that.ReturnAccessSearch.UnitId.slice(0,2) != 'UN' && that.ReturnAccessSearch.UnitId != ''){
        ElMessage.warning({
          showClose: true,
          message: "功能单元编号应以UN开头！",
          type: "warning",
          center: true
        })
      }
      if(that.ReturnAccessSearch.UnitId == '' && that.ReturnAccessSearch.ExpId == '' && that.ReturnAccessSearch.UnitName == '' && that.ReturnAccessSearch.StateIf == false)
      {
        that.$notify({
          title: '提示',
          message: '您未选择查询条件，将为您呈现所有条目',
          type: 'warning',
          customClass: 'backgroundClass'
        });
      }
      let flag = false;
      if (that.ReturnAccessSearch.StateIf == true)
        flag = true;
      get('/proPartialInfo/getInfo', {
        exp_id: that.ReturnAccessSearch.ExpId,
        pro_id: that.ReturnAccessSearch.UnitId,
        pro_name: that.ReturnAccessSearch.UnitName,
        pro_state: state}).then(function (res) {
        if(res.code == 0)
        {
          ElMessage.warning({
            showClose: true,
            message: "未能找到符合要求的条目!",
            type: "warning",
            center: true
          })
        }
        if (res.code === 1){
          res.data.forEach(function (item) {
            var tmp = {
              labid:item.exp_id,
              procedureid:item.pro_id,
              procedurename:item.pro_name,
              procedurestate:item.pro_state
            };
            if(flag) {
              if(tmp.procedurestate != '归还完成'&& tmp.procedurestate != '暂被撤销'){
                that.tableData.push(tmp);
              }
            }
            else that.tableData.push(tmp);
          })
          return true;
        }}
      );
    },
    onSubmit_two() {
      let that = this;
      let state = '';
      that.tableProManage = [];
      if(that.ProManageSearch.ExpId.slice(0,3) != 'EXP' && that.ProManageSearch.ExpId != ''){
        ElMessage.warning({
          showClose: true,
          message: "实验编号应以EXP开头！",
          type: "warning",
          center: true
        })
      }
      if(that.ProManageSearch.UnitId.slice(0,2) != 'UN' && that.ProManageSearch.UnitId != ''){
        ElMessage.warning({
          showClose: true,
          message: "功能单元编号应以UN开头！",
          type: "warning",
          center: true
        })
      }
      if(that.ProManageSearch.UnitId == '' && that.ProManageSearch.ExpId == '' && that.ProManageSearch.UnitName == '' && that.ProManageSearch.StateIf == false)
      {
        that.$notify({
          title: '提示',
          message: '您未选择查询条件，将为您呈现所有条目',
          type: 'warning',
          customClass: 'backgroundClass'
        });
      }
      let flag = false;
      if (that.ProManageSearch.StateIf == true)
        flag = true;
      get('/proPartialInfo/getInfo', {
        exp_id: that.ProManageSearch.ExpId,
        pro_id: that.ProManageSearch.UnitId,
        pro_name: that.ProManageSearch.UnitName,
        pro_state: state}).then(function (res) {
        if(res.code == 0)
        {
          ElMessage.warning({
            showClose: true,
            message: "未能找到符合要求的条目!",
            type: "warning",
            center: true
          })
        }
        if (res.code === 1){
          console.log(res.data);
          res.data.forEach(function (item) {
            var tmp = {
              labid:item.exp_id,
              procedureid:item.pro_id,
              procedurename:item.pro_name,
              procedurestate:item.pro_state
            };
            if(flag) {
              if(tmp.procedurestate != '尚未开始' && tmp.procedurestate != '实验完成' && tmp.procedurestate != '归还完成'&& tmp.procedurestate != '暂被撤销' && tmp.procedurestate != '查验完成' && tmp.procedurestate != '申请完成'){
                that.tableProManage.push(tmp);
              }
            }
            else that.tableProManage.push(tmp);
          })
          return true;
        }}
      );
    },
    handleDelete(index) {
      // 设置类似于console类型的功能
      let that = this;
      that.$confirm("该操作将撤销该单元并反馈, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
          .then(() => {
            // 移除对应索引位置的数据，可以对row进行设置向后台请求删除数据
            if(index.procedurestate === '实验完成' ||
                index.procedurestate === '查验完成'||
                index.procedurestate === '归还完成'||
                index.procedurestate === '尚未开始'){
              ElMessage.warning({
                showClose: true,
                message: "该实验顺利进行，无法撤销！",
                type: "warning",
                center: true
              })
              return;
            }
            get('/proPartialInfo/updateState', {
              exp_id: index.labid,
              pro_id: index.procedureid,
              pro_state: '暂被撤销',
              other_info: '该实验已被撤销，请及时处理后续事务'}).then(function (res) {
                console.log(res);
              if(res.code === 1){
                ElMessage.success({
                  showClose: true,
                  message: "撤销成功！",
                  type: "success",
                  center: true
                })
              }
              else{
                ElMessage.warning({
                  showClose: true,
                  message: "撤销失败,未能找到相应记录!",
                  type: "warning",
                  center: true
                })
              }

            })
            that.tableProManage.splice(index, 1);
          })
          .catch(() => {
            that.$message({
              type: "info",
              message: "已取消删除"
            });
          });
    },
    handleDeleteAll(index) {
      // 设置类似于console类型的功能
      let that = this;
      Date.prototype.format = function(fmt){
        var o = {
          "M+" : this.getMonth()+1,                 //月份
          "d+" : this.getDate(),                    //日
          "h+" : this.getHours(),                   //小时
          "m+" : this.getMinutes(),                 //分
          "s+" : this.getSeconds(),                 //秒
          "q+" : Math.floor((this.getMonth()+3)/3), //季度
          "S"  : this.getMilliseconds()             //毫秒
        };

        if(/(y+)/.test(fmt)){
          fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
        }

        for(var k in o){
          if(new RegExp("("+ k +")").test(fmt)){
            fmt = fmt.replace(
                RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
          }
        }

        return fmt;
      }
      var now = new Date();
      var nowStr = now.format("yyyy-MM-dd hh:mm:ss");
      that.$confirm("该操作将永久撤销该单元及其同一实验下的所有单元, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
          .then(() => {
            if(index.procedurestate === '实验完成' || index.procedurestate === '查验完成'
                || index.procedurestate === '查验完成' || index.procedurestate === '尚未开始'){
              ElMessage.warning({
                showClose: true,
                message: "该实验顺利进行，无法撤销！",
                type: "warning",
                center: true
              })
              return;
            }
            get('/proPartialInfo/allDelete', {
              exp_id: index.labid,
              cur_time: nowStr,
              pro_state: '暂被撤销',
              other_info: '该实验已被撤销，请及时处理后续事务'}).then(function (res) {
              console.log(res);
              if(res.data >= 1){
                ElMessage.success({
                  showClose: true,
                  message: "撤销成功！",
                  type: "success",
                  center: true
                })
              }
              else{
                ElMessage.warning({
                  showClose: true,
                  message: "撤销失败,未能找到相应记录!",
                  type: "warning",
                  center: true
                })
              }

            })
            that.tableProManage.splice(index, 1);
            that.$message({
              type: "success",
              message: "撤销成功!"
            });
          })
          .catch(() => {
            that.$message({
              type: "info",
              message: "已取消撤销！"
            });
          });
    },
    tableRowClassName({row}) {
      if (row.procedurestate === '实验完成') {
        return 'green-row';
      } else if (row.procedurestate === '归还完成' || row.procedurestate === '查验完成' || row.procedurestate === '申请完成') {
        return 'blue-row';
      } else if (row.procedurestate === '暂被撤销') {
        return 'gray-row';
      } else if (row.procedurestate === '尚未开始') {
        return 'white-row';
      }
      else {
        return 'red-row';
      }
    },
    submitForm() {
      let that = this;
      console.log(that.ruleForm.unitstate);
      if (that.ruleForm.unitstate !== '实验完成' &&  that.ruleForm.unitstate !== '数据有误') {
        ElMessage.warning({
          showClose: true,
          message: "您没有权限提交此类信息",
          type: "warning",
          center: true
        })
        return;
      }
      else {
        get('/proPartialInfo/updateState', {
          lab_id: that.ruleForm.expid,
          pro_id: that.ruleForm.unitid,
          pro_state: that.ruleForm.unitstate,
          other_info: that.ruleForm.textarea}).then(function (res) {
          if(res.code === 1){
            ElMessage.success({
              showClose: true,
              message: "状态更新成功！",
              type: "success",
              center: true
            })
          }
          else{
            ElMessage.warning({
              showClose: true,
              message: "状态更新失败,未能找到相应记录!",
              type: "warning",
              center: true
            })
          }

        })

      }}}}
</script>

<style>
.el-table .red-row {
  background: #FFDEDE;
}

.el-table .green-row {
  background: #C8FFCA;
}

.el-table .blue-row {
  background: #C8EAFB;
}

.el-table .white-row {
  background: #ffffff;
}

.el-table .grey-row {
  background: #E1E4E5;
}

.backgroundClass{
  background-color: #ffffff;
}
</style>